<?php
declare (strict_types=1);

namespace app\exam\logic;

use app\common\exception\LogicException;
use app\exam\model\Topic as TopicModel;

/**
 * 试题逻辑
 * @method orderRaw(string $string)
 */
class Topic extends TopicModel
{

    /**
     * 获取试题信息及选项
     * Author 亓官雨树<lucky.max@foxmail.com>
     * Date 2021-02-04
     *
     * @param  [type] $param [description]
     * @return array [type]        [description]
     */
    public function getTopicInfo($param): array
    {
        // 数据验证
        $this->getValidate()->scene('topic_info')->failException()->check($param);
        // 参数
        $topic_id = $param['topic_id'];
        $origin   = $param['origin'];
        $analyze  = !in_array($origin, [3, 4]);

        return $this->getTopicInfoById($topic_id, $analyze);
    }

    /**
     * 获取试题信息
     * Author 亓官雨树<lucky.max@foxmail.com>
     * Date 2021-02-04
     *
     * @param string $topic_id
     * @param bool   $analyze
     * @return array [type]     [description]
     */
    public function getTopicInfoById(string $topic_id, bool $analyze = true): array
    {
        $topic_id  = explode(',', $topic_id);
        $topics    = [];
        // $hash_name = $analyze ? 'topics_analyze_hash' : 'topics_hash';

        foreach ($topic_id as $id) {
            // $redis  = Cache::store('redis')->handler();
            // $res    = $redis->hGet($hash_name, $id);

            // if ( $res ) {

            // 	$topic = unserialize($res);
            // 	$topic->collected = app(TopicCollect::class)->hasUserCollectedTopic($id);
            // 	$topics[] = $topic;

            // } else {

            $field = 'id,title,question_type,point';
            $analyze && $field .= ',analyze';

            $topic = $this->field($field . ',completion_position')->findOrEmpty($id);

            if ($topic->isEmpty()) throw new LogicException('试题错误');

            $topic->points = app(Point::class)->withoutGlobalScope()->where('id', 'IN', $topic->point)->column('title');

            $topic = $this->parseTopicOptions($topic, $field, $analyze);

            $topic->material = app(Common::class)->parseMaterial($topic->title ?: '');
            $topic->title    = app(Common::class)->removeMaterial($topic->title ?: '');

            // $redis->hSet($hash_name, $id, serialize($topic));

            $topic->collected = app(TopicCollect::class)->hasUserCollectedTopic($id);

            $topics[] = $topic;
            // }
        }

        return $topics;
    }

    /**
     * 解析选项
     * Author 亓官雨树<lucky.max@foxmail.com>
     * Date 2021-02-03
     *
     * @param $topic
     * @param $field
     * @param $analyze
     * @return mixed [type]        [description]
     */
    public function parseTopicOptions($topic, $field, $analyze)
    {
        switch ($topic->question_type) {
            case 1:
            case 2:
            case 3:
            case 4:
                $topic->topic_level = 1;
                $topic->options     = app(Option::class)->getTopicOptions($topic->id, 1, $analyze);
                break;

            case 5:
                $topic->topic_level = 1;
                $topic->options     = app(OptionCompletion::class)->getTopicOptions($topic->id);
                break;

            case 6:
            case 7:
                $topic->topic_level = 2;
                $question_type_arr  = self::getQuestionTypeArr();
                $topic->topics      = app(Material::class)->whereTopicId($topic->id)->field($field)->order('sort')->select()
                    ->each(function ($item) use ($analyze, $question_type_arr) {
                        $item->material           = app(Common::class)->parseMaterial($item->title ?: '');
                        $item->title              = app(Common::class)->removeMaterial($item->title ?: '');
                        $item->options            = app(Option::class)->getTopicOptions($item->id, 2, $analyze);
                        $item->question_type_text = $question_type_arr[$item->question_type];
                        $item->topic_level        = 2;
                        if (8 == $item->question_type) {
                            $item->reference_answer = app(Short::class)->getValueByTopicId($item->id, 2);
                        }
                    });
                break;

            case 8:
                $topic->topic_level      = 1;
                $topic->reference_answer = app(Short::class)->getValueByTopicId($topic->id);
                break;

            default:
                # code...
                break;
        }

        return $topic;
    }

    /**
     * 增加试题作答次数
     * Author: 亓官雨树 <lucky.max@foxmail.com>
     * Date: 22/02/15
     *
     * @param int $topicId
     */
    public function addTopicAnswerNum(int $topicId)
    {
        $topic = $this->findOrEmpty($topicId);
        if ($topic->isEmpty()) return;
        $topic->answer_num += 1;
        $topic->save();
    }
}
